<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Android, Java">










<meta name="description" content="哈哈~">
<meta name="keywords" content="zachaxy">
<meta property="og:type" content="website">
<meta property="og:title" content="zachaxy">
<meta property="og:url" content="https://zachaxy.github.io/page/11/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="哈哈~">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="zachaxy">
<meta name="twitter:description" content="哈哈~">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/page/11/">





  <title>zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">

  <section id="posts" class="posts-expand">









  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/07/手写JVM系列-2-参数解析/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/07/手写JVM系列-2-参数解析/" itemprop="url">手写JVM系列(2)-参数解析</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-07T10:53:02+08:00">
                2017-05-07
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,257
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">






          <p>这一章节开始<code>JVM</code>的编写,首先解决第一个问题,就是如何运行java程序，回想最开始学java时，写一个Hello.java的程序，使用<code>javac Hello.java</code>将源代码转换为class文件，然后使用<code>java Hello</code>运行程序。JVM是只认class文件的，如果想让JVM运行该Hello程序，就要通过java命令。本节将介绍java命令的常用方法，并实现java命令的解析。最终通过命令参数，读取对应的class数据。本节的代码均在<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">classpath包</a>下</p>
          <!--noindex-->
          <div class="post-button text-center">
            <a class="btn" href="/2017/05/07/手写JVM系列-2-参数解析/#more" rel="contents">
              阅读全文 &raquo;
            </a>
          </div>
          <!--/noindex-->


    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/06/手写JVM系列-1-准备工作/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/06/手写JVM系列-1-准备工作/" itemprop="url">手写JVM系列(1)-准备工作</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-06T22:20:06+08:00">
                2017-05-06
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,445
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">






          <blockquote>
<p>本系列文章主要根据张秀宏老师的—— 《自己动手写 java 虚拟机》一书所做的笔记。该书实现了大部分 JVM 的功能，包括class文件解析、类加载、指令集、解释器、方法调用、数组和字符串的处理、异常处理等。这本书可以说是了解 Java 虚拟机最浅显易懂的书籍，随书提供了每个章节的代码，可以完美运行。但是这本书所附带的代码是用 go 语言书写的，如果想要看懂这本书的代码，首先要学会 go 语言的基本语法。这边博客记录了在阅读这本书之前的准备工作。我在练习中是根据张老师的代码用 Java 语言又实现了一遍。虽然用 Java 语言在实现一个自己的虚拟机，然后跑在自带的虚拟机上有点滑稽，但是重点还是了解虚拟机内部的基本原理。</p>
</blockquote>
<p>贴出张秀宏老师这本书的<a href="https://github.com/zxh0/jvmgo-book" target="_blank" rel="noopener">代码</a></p>
          <!--noindex-->
          <div class="post-button text-center">
            <a class="btn" href="/2017/05/06/手写JVM系列-1-准备工作/#more" rel="contents">
              阅读全文 &raquo;
            </a>
          </div>
          <!--/noindex-->


    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/04/26/字符串匹配-RK算法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/04/26/字符串匹配-RK算法/" itemprop="url">字符串匹配--RK算法</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-26T09:32:04+08:00">
                2017-04-26
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,549
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>Rabin-Karp采用了把字符进行预处理，也就是对每个字符进行对应进制数并取模运算，类似于通过某种哈希函数计算其函数值，比较的是每个字符的函数值。预处理时间O(m)，理论匹配时间是O((n-m+1)m)。这里要乘以m是考虑到对hash值相同的进行一次校验;</p>
<p>由于hash冲突的存在，当hash值相同的时候，还是需要朴素算法来进行必要的比较,所以时间复杂性为O（m<em>n）。但是*</em>现实中**hash冲突出现的可能性不是很大，所以相比较而言，复杂性还是比较小的，仅仅为O(m+n)</p>
</blockquote>
<h1 id="初始化变量"><a href="#初始化变量" class="headerlink" title="初始化变量"></a>初始化变量</h1><ul>
<li>待匹配的字符串<code>s</code></li>
<li>待匹配的子串<code>m</code></li>
<li><code>m</code>的长度为<code>M</code></li>
<li><code>R</code>进制:如果字符串中所有的字符都是小写英文字母,那么就是26进制,如果都是数字,那么就是10进制,如果没有说明,那么就以<code>ASCII表</code>256进制来计算</li>
<li><code>Q</code>随机的大素数,在不溢出的情况下选择一个尽可能大的素数</li>
<li><code>RM</code>这里并不是<code>R*M</code>而是 $R^{M-1}$%Q</li>
<li><code>hash()</code>函数,对<code>m</code>进行运算,得到目标hash值</li>
<li><code>targetHash = hash(m)</code></li>
</ul>
<h1 id="基本思想"><a href="#基本思想" class="headerlink" title="基本思想"></a>基本思想</h1><p>这里以下面参数为例,讲解RK算法的基本思想;</p>
<ul>
<li><code>s=3141592653589793</code></li>
<li><code>m=26535</code></li>
<li><code>M=5</code></li>
<li><code>Q=997</code></li>
<li><code>hash(x) = x % Q</code></li>
<li><code>targetHash = 26535 % 997 = 613</code></li>
</ul>
<p>那么在接下来的匹配中可以得出</p>
<table>
<thead>
<tr>
<th align="center">i</th>
<th align="center">0</th>
<th align="center">1</th>
<th align="center">2</th>
<th align="center">3</th>
<th align="center">4</th>
<th align="center">5</th>
<th align="center">6</th>
<th align="center">7</th>
<th align="center">8</th>
<th align="center">9</th>
<th align="center">10</th>
<th align="center">11</th>
<th align="center">12</th>
<th align="center">13</th>
</tr>
</thead>
<tbody><tr>
<td align="center">0</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center">508</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">1</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center">201</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">2</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center">715</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">3</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center">971</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">4</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center">442</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">5</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center">929</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">6</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center">613  (匹配)</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
</tbody></table>
<ol>
<li>从<code>s</code>第0位开始,取前<code>M</code>位,用<code>hash()</code>方法计算出其值与<code>targetHash</code>进行对比</li>
<li>如果相等,那么这<code>M</code>位可能会匹配上,</li>
<li>如果不相等,那么<code>s</code>后移一位,继续计算相应<code>M</code>为的<code>hash()</code>,进行对比</li>
</ol>
<p>以上过程只是对RK算法的一个简单描述,注意到每次也是后移一位,计算<code>hash()</code>值,因为我们的s中都是数字,可以很方便的来计算出<code>hash</code>值,如果是字母的话,计算hash值可能就不是那么容易了,这也是RK算法要解决的核心问题,因为我们大部分情况下面对的都是字符串,我们需要将字符串转换为对应的数值,如何转换呢?那就是接下来用到的散列函数</p>
<h1 id="计算散列函数"><a href="#计算散列函数" class="headerlink" title="计算散列函数"></a>计算散列函数</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">long</span> <span class="title">hash</span><span class="params">(String key, <span class="keyword">int</span> M)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">long</span> h = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; M; i++) &#123;</span><br><span class="line">      	h = (R * h + key.charAt(i)) % Q;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> h;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该函数的目标是计算一次<code>m</code>的<code>targetHash</code>,计算一次<code>s</code>的前<code>M</code>位的<code>hash</code>,仅此两次调用,那么我们不是每次都要将<code>s</code>的游标后移一位,在计算其hash值吗?这就是RK算法巧妙的地方,如果当前不匹配,那么后移一位,其hash值</p>
<p>*<em>注意: *</em>再次强调<code>Q</code>一定要是一个尽可能大的素数,以减少冲突;</p>
<h1 id="关键思想"><a href="#关键思想" class="headerlink" title="关键思想"></a>关键思想</h1><p>RK算法的基础是对于所有位置<code>i</code>,不调用hash()方法,高效计算文本中<code>i+1,</code></p>
<p>我们用 $t_i$表示<code>s.charAt(i)</code>,那么<code>s</code>其实于<code>i</code>,长度为<code>M</code>的数值(注意此处并不是hash值)为:</p>
<p>$$x_i = t_iR^{M-1}+t_{i+1}R^{M-2}+…+t_{i+M-1}R^0$$              <code>(1)</code></p>
<p>$h(x_i)=x_i mod Q$                                    <code>(2)</code></p>
<p>$$x_{i+1}=(x_i-t_iR^{M-1})R+t_{i+M}$$                    <code>(3)</code></p>
<p><code>(a + b) % c = ((a % c)+(b % c)) % c</code>                <code>(4)</code></p>
<p><code>(a - b) % c = ((a % c)-(b % c)) % c</code>                <code>(5)</code></p>
<p><code>(a * b) % c = ((a % c)*(b % c)) % c</code>                <code>(6)</code></p>
<p>基于以上公式,可以方便的得到<code>search()</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//返回匹配成功的索引;</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">search</span><span class="params">(String txt)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> N = txt.length();</span><br><span class="line">    <span class="keyword">long</span> txtHash = hash(txt, M); <span class="comment">//计算txt文本的前M位的hash值</span></span><br><span class="line">    <span class="keyword">if</span> (targetHash == txtHash &amp;&amp; check(<span class="number">0</span>)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>; <span class="comment">//在开始位置处就匹配成功;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = M; i &lt; N; i++) &#123;</span><br><span class="line">        <span class="comment">//+Q并不影响对其本质的区别;因为 Q % Q = 0</span></span><br><span class="line">        txtHash = (txtHash + Q - RM * txt.charAt(i - M) % Q) % Q;  <span class="comment">//是为了防止出现负数吧...</span></span><br><span class="line">        txtHash = (txtHash * R + txt.charAt(i)) % Q;</span><br><span class="line">        <span class="keyword">if</span> (targetHash == txtHash) &#123;</span><br><span class="line">            <span class="keyword">if</span> (check(i - M + <span class="number">1</span>)) &#123;</span><br><span class="line">                <span class="keyword">return</span> i - M + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Author: zhangxin</span></span><br><span class="line"><span class="comment"> * Time: 2017/4/12 0012.</span></span><br><span class="line"><span class="comment"> * Desc: 基于指纹的字符匹配算法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RabinKarp</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> targetHash;  <span class="comment">//模拟字符串的散列值</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> M;          <span class="comment">//模拟字符串的长度;</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> Q;          <span class="comment">//大素数</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> R = <span class="number">256</span>;    <span class="comment">//字母表大小;这里最好设置为可以定制的吧;</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> RM;        <span class="comment">//R^(M-1)%Q;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RabinKarp</span><span class="params">(String pat)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.M = pat.length();</span><br><span class="line">        Q = <span class="number">997</span>; <span class="comment">//或者你自己写一个随机的素数表;</span></span><br><span class="line">        RM = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//注意这里是从1开始,到M-1,[1,M-1],一共M-1个数;</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; M; i++) &#123;</span><br><span class="line">            RM = (R * RM) % Q;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        targetHash = hash(pat, M);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">long</span> <span class="title">hash</span><span class="params">(String key, <span class="keyword">int</span> M)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> res = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; M; i++) &#123;</span><br><span class="line">            res = (R * res + key.charAt(i)) % Q;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//这个方法一般不用,从概率上来说,不用再check,如果你不放心,可以添加上字符逐一对比的代码</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">check</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//返回匹配成功的索引;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">search</span><span class="params">(String txt)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> N = txt.length();</span><br><span class="line">        <span class="keyword">long</span> txtHash = hash(txt, M); <span class="comment">//计算txt文本的前M位的hash值</span></span><br><span class="line">        <span class="keyword">if</span> (targetHash == txtHash &amp;&amp; check(<span class="number">0</span>)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>; <span class="comment">//在开始位置处就匹配成功;</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = M; i &lt; N; i++) &#123;</span><br><span class="line">            <span class="comment">//+Q并不影响对其本质的区别; Q%Q=0</span></span><br><span class="line">            txtHash = (txtHash + Q - RM * txt.charAt(i - M) % Q) % Q;  <span class="comment">//是为了防止出现负数吧...</span></span><br><span class="line">            txtHash = (txtHash * R + txt.charAt(i)) % Q;</span><br><span class="line">            <span class="keyword">if</span> (targetHash == txtHash) &#123;</span><br><span class="line">                <span class="keyword">if</span> (check(i - M + <span class="number">1</span>)) &#123;</span><br><span class="line">                    <span class="keyword">return</span> i - M + <span class="number">1</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="优缺点"><a href="#优缺点" class="headerlink" title="优缺点"></a>优缺点</h1><p>优点:</p>
<ol>
<li>它可以用来检测抄袭，因为它能够处理多模式匹配(多个不同长度的<code>m</code>)；</li>
<li>虽然在理论上并不比暴力匹配法更优，但在实际应用中它的复杂度仅为O(n+m);</li>
<li>如果能够选择一个好的哈希函数，它的效率将会很高，而且也易于实现。</li>
</ol>
<p>缺点:</p>
<ol>
<li>有许多字符串匹配算法的复杂度小于O(n+m)；</li>
<li>有时候它和暴力匹配法一样慢，并且它需要额外空间。</li>
</ol>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/04/26/字符串匹配-KMP算法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/04/26/字符串匹配-KMP算法/" itemprop="url">字符串匹配--KMP算法</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-26T09:21:26+08:00">
                2017-04-26
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,611
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p><strong>Knuth-Morris-Pratt 字符串查找算法</strong>（常简称为“<strong>KMP算法</strong>”）可在一个主“文本字符串”<code>s</code>内查找一个“词”<code>m</code>的出现位置。此算法通过运用对这个词在不匹配时本身就包含足够的信息来确定下一个匹配将在哪里开始的发现，从而避免重新检查先前匹配的字符。</p>
</blockquote>
<h1 id="初始化变量"><a href="#初始化变量" class="headerlink" title="初始化变量"></a>初始化变量</h1><p>待查找的字符串:s<br>要匹配的字符串:m    </p>
<h1 id="普通的做法"><a href="#普通的做法" class="headerlink" title="普通的做法"></a>普通的做法</h1><p>字符串匹配算法最常规的思路是在s中一个字符一个字符的与m中的第一个字符比较,匹配了说明找到了源头(i)这个i接下来很可能会与m完全匹配的,再比较各自接下来一个字符,如果匹配不上,说明上次找的i不是我们想要的源头,接着怎么办?从i+1开始,看i+1是否有可能是这个源头.</p>
<h2 id="普通做法的缺点"><a href="#普通做法的缺点" class="headerlink" title="普通做法的缺点"></a>普通做法的缺点</h2><p>时间复杂度高,造成这个的原因是因为在匹配过程中,虽然没有完全匹配上.但是很可能已经匹配了一部分,已经匹配上了的这一小部分并没有被充分利用起来;</p>
<h1 id="KMP算法"><a href="#KMP算法" class="headerlink" title="KMP算法"></a>KMP算法</h1><blockquote>
<p>充分利用在匹配过程中,没有完全匹配上但是已经匹配上一部分的资源.</p>
</blockquote>
<h2 id="几个概念"><a href="#几个概念" class="headerlink" title="几个概念:"></a>几个概念:</h2><p>下面的概念都是针对一个字符串而言的,eg:一个字符串为abc</p>
<p>前缀:a,ab,包含首字符,但不包含末字符的字符串;<br>后缀:c,bc,包含末字符,但不包含首字符的字符串;       </p>
<h2 id="具体步骤"><a href="#具体步骤" class="headerlink" title="具体步骤"></a>具体步骤</h2><h3 id="构造辅助数组"><a href="#构造辅助数组" class="headerlink" title="构造辅助数组"></a>构造辅助数组</h3><ol>
<li>拿到m字符串,生成一个与m等长的整型数组next[]</li>
<li>初始化next[0] = -1,next[1] = 0</li>
<li>从2开始遍历m,next[i]的值就是 字符串 m[0~i-1] 的相同的最长前缀和最长后缀的长度</li>
</ol>
<h3 id="匹配过程"><a href="#匹配过程" class="headerlink" title="匹配过程"></a>匹配过程</h3><ul>
<li>开始匹配,定义两个游标,si和mi,初始均为0</li>
<li>如果能匹配上,si++,mi++</li>
<li>如果匹配不上,注意此时的隐含条件是mi之前的已经匹配上了,我们想下次移动的时候不是把m移动到上次匹配s的起止位置之后的一个字符处,而是看m[0~i-1]中的前缀和后缀是不是有一样的地方,这样就可以重复利用,这不就是next数组的作用吗?因此查看此时的next数组,将mi = next[mi];接下来当然从si和mi继续匹配,看能否匹配了</li>
<li>如果next[mi] == -1,表明连m的第一个字符都匹配不上,那么只能si++;</li>
</ul>
<h3 id="源代码"><a href="#源代码" class="headerlink" title="源代码"></a>源代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Author: zhangxin</span></span><br><span class="line"><span class="comment"> * Time: 2016/12/16 0016.</span></span><br><span class="line"><span class="comment"> * Desc:KMP算法;</span></span><br><span class="line"><span class="comment"> * 核心是next[]数组的计算,以及在匹配过程中如何使用next,感性上的理解是需要移动数组的,但在实际的使用中时只需要修改si与mi即可;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">KMP</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">getIndexOf</span><span class="params">(String s, String m)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (s == <span class="keyword">null</span> || m == <span class="keyword">null</span> || m.length() &lt; <span class="number">1</span> || s.length() &lt; m.length()) &#123;</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">char</span>[] ss = s.toCharArray();</span><br><span class="line">        <span class="keyword">char</span>[] ms = m.toCharArray();</span><br><span class="line">        <span class="keyword">int</span> si = <span class="number">0</span>; <span class="comment">//str中当前i的位置;其实真正的游标是si,你想匹配字符串的时候,主标是s掌控的;</span></span><br><span class="line">        <span class="keyword">int</span> mi = <span class="number">0</span>;<span class="comment">//match中当前i的位置;</span></span><br><span class="line">        <span class="keyword">int</span>[] next = getNextArray(ms);</span><br><span class="line">        <span class="keyword">while</span> (si &lt; ss.length &amp;&amp; mi &lt; ms.length) &#123;</span><br><span class="line">            <span class="keyword">if</span> (ss[si] == ms[mi]) &#123;</span><br><span class="line">                <span class="comment">//当前字符能匹配上,si,mi都前移一位;</span></span><br><span class="line">                si++;</span><br><span class="line">                mi++;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (next[mi] == -<span class="number">1</span>) &#123;</span><br><span class="line">                <span class="comment">//匹配不上,mi=0,第一个字符都匹配不上,si前移一位;</span></span><br><span class="line">                si++;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//前面还是有部分能匹配上的,mi=next[mi];si不变;</span></span><br><span class="line">                mi = next[mi];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> mi == ms.length ? si - mi : -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/***</span></span><br><span class="line"><span class="comment">     * 获取nextArr数组</span></span><br><span class="line"><span class="comment">     * nextArr[0] = -1;因为如果第一个字符都匹配不上,那么match整体后移1位;</span></span><br><span class="line"><span class="comment">     * nextArr[1] = 0;因为第一个字符没有前缀也没有后缀,肯定是0</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ms match字符串对应的字符数组</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span>[] getNextArray(<span class="keyword">char</span>[] ms) &#123;</span><br><span class="line">        <span class="keyword">if</span> (ms.length == <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="keyword">int</span>[]&#123;-<span class="number">1</span>&#125;;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span>[] next = <span class="keyword">new</span> <span class="keyword">int</span>[ms.length];</span><br><span class="line">        next[<span class="number">0</span>] = -<span class="number">1</span>;</span><br><span class="line">        next[<span class="number">1</span>] = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> pos = <span class="number">2</span>; <span class="comment">//当前位置;</span></span><br><span class="line">        <span class="keyword">int</span> cn = <span class="number">0</span>; <span class="comment">//前缀开始匹配的位置;</span></span><br><span class="line">        <span class="keyword">while</span> (pos &lt; next.length) &#123;</span><br><span class="line">            <span class="keyword">if</span> (ms[pos - <span class="number">1</span>] == ms[cn]) &#123;</span><br><span class="line">                next[pos++] = ++cn;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (cn &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">//遇到某个字符匹配不上了,那么直接下次不能再用之前的了,而是将cn置0</span></span><br><span class="line">                <span class="comment">// next先不设置,cn==0后,再去进入循环,从头匹配;也许能匹配的上;</span></span><br><span class="line">                <span class="comment">//cn = next[cn]; 不看这一句,删掉;</span></span><br><span class="line">                cn = <span class="number">0</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                next[pos++] = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> next;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        String str = <span class="string">"abcabcababaccc"</span>;</span><br><span class="line">        String match = <span class="string">"ababa"</span>;</span><br><span class="line">        <span class="comment">/*str = "abxxxabwwab";</span></span><br><span class="line"><span class="comment">        match = "xab";*/</span></span><br><span class="line">        System.out.println(getIndexOf(str, match));</span><br><span class="line">        System.out.println(str.indexOf(match));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="next-数组深入分析"><a href="#next-数组深入分析" class="headerlink" title="next[]数组深入分析"></a>next[]数组深入分析</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">分析 match = &quot;ababa&quot;  =&gt; next[5]</span><br><span class="line">next[i]的含义:match[0~i-1]组成的字符串,最长前缀(不包含最后一个字符)和最长后缀(不包含第一个字符)匹配上的长度;</span><br><span class="line">初始化:</span><br><span class="line">next[0] = -1;显然match[0~0-1]无意义,令其等于-1,代表第一个字符都匹配不上,match直接右移一位</span><br><span class="line">next[1] = 0;显然match[0~1-1]就是match[0],只有一个字符,没有前缀也没有后缀;所以next[1]=0;</span><br><span class="line">接下来开始匹配了,match[2]这个位置前面已经有两个字符了,可能前两个字符相等,那么next[2]=1,不相等,next[2]=0</span><br><span class="line">可以发现的是,第一次匹配一定是match[i-1]和match[0]匹配;接下来如果再能匹配,因为match[i-1]和match[0]已匹配,match[i]和match[1]也能匹配了</span><br><span class="line"></span><br><span class="line">ababa的next数组;</span><br><span class="line">    0 1 2 3 4</span><br><span class="line">    a b a b a</span><br><span class="line">   -1 0 0 1 2</span><br><span class="line"></span><br><span class="line">接下来拿ababcccc与ababe来匹配,ababe的next数组为&#123;-1,0,0,1,2&#125;,和上面的ababa是一样的;</span><br><span class="line">一开始是可以匹配的,当si = mi = 4 时,匹配不上了,这个时候的隐含条件就是m中的[0~mi-1]是都能匹配上的</span><br><span class="line">这时候找next[mi],next[4]=2,说明mi之前的字符串中前两个和最后两个可以匹配上,所以下次比的时候,si = 4,mi = 2,从m[3]字符处开始匹配;</span><br></pre></td></tr></table></figure>



    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/04/13/Dijkstra算法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/04/13/Dijkstra算法/" itemprop="url">Dijkstra算法</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-13T15:12:38+08:00">
                2017-04-13
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,254
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>Dijkstra算法,给出一个邻接矩阵和一个起始点,返回这个其实点到邻接矩阵中各个点的最短距离</p>
<p>使用了广度优先搜索解决非负权有向图的单源最短路径问题，算法最终得到一个最短路径树（一个节点到其他所有节点的最短路径）。<br>该算法常用于路由算法或者作为其他图算法的一个子模块。主要特点是以起始点为中心向外层层扩展，直到扩展到终点为止。</p>
</blockquote>
<hr>
<p>基本用法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dijkstra</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> M = Integer.MAX_VALUE; <span class="comment">//此路不通</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//邻接矩阵,单向连接;</span></span><br><span class="line">        <span class="keyword">int</span>[][] weight = &#123;</span><br><span class="line">                &#123;<span class="number">0</span>, <span class="number">10</span>, M, <span class="number">30</span>, <span class="number">100</span>&#125;,</span><br><span class="line">                &#123;M, <span class="number">0</span>, <span class="number">50</span>, M, M&#125;,</span><br><span class="line">                &#123;M, M, <span class="number">0</span>, M, <span class="number">10</span>&#125;,</span><br><span class="line">                &#123;M, M, <span class="number">20</span>, <span class="number">0</span>, <span class="number">60</span>&#125;,</span><br><span class="line">                &#123;M, M, M, M, <span class="number">0</span>&#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置起始点,这里将0设置为起始点,接下来要做的动作是寻找整个图中所有点距离0最近的距离;</span></span><br><span class="line">        <span class="keyword">int</span> start = <span class="number">0</span>;</span><br><span class="line">        <span class="comment">//最短路径的数组,长度为0,保存了0到n个点的最短距离,当然第一个值是0到0的距离,距离为0;</span></span><br><span class="line">        <span class="keyword">int</span>[] shortPath = dijkstra(weight, start);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//打印0到各点最近的距离;</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; shortPath.length; i++)</span><br><span class="line">            System.out.println(<span class="string">"从"</span> + start + <span class="string">"出发到"</span> + i + <span class="string">"的最短距离为："</span> + shortPath[i]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/***</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> weight 有向图的权重矩阵</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> start  一个起点编号start（从0编号，顶点存在数组中）</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 返回一个int[] 数组，表示从start到它的最短路径长度</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span>[] dijkstra(<span class="keyword">int</span>[][] weight, <span class="keyword">int</span> start) &#123;</span><br><span class="line">        <span class="keyword">int</span> n = weight.length;         <span class="comment">//顶点个数</span></span><br><span class="line">        <span class="keyword">int</span>[] shortPath = <span class="keyword">new</span> <span class="keyword">int</span>[n];  <span class="comment">//保存start到其他各点的最短路径,最后作为返回值被返回;</span></span><br><span class="line">        String[] path = <span class="keyword">new</span> String[n];  <span class="comment">//保存start到其他各点最短路径的字符串描述;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//初始化从start到各个节点的最优路径图</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            path[i] = start + <span class="string">"--&gt;"</span> + i;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//或者用一个boolean类型的数组表示,是否已经访问过;</span></span><br><span class="line">        <span class="keyword">int</span>[] visited = <span class="keyword">new</span> <span class="keyword">int</span>[n];   <span class="comment">//标记当前该顶点的最短路径是否已经求出,1表示已求出</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//初始化，第一个顶点已经求出</span></span><br><span class="line">        shortPath[start] = <span class="number">0</span>;</span><br><span class="line">        visited[start] = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//最外层循环,一共n个节点,要找到start节点到其他n-1个节点的最短距离,因此这里需要循环n-1次;</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> count = <span class="number">1</span>; count &lt; n; count++) &#123;   <span class="comment">//要加入n-1个顶点</span></span><br><span class="line">            <span class="keyword">int</span> k = -<span class="number">1</span>;        <span class="comment">//选出一个距离初始顶点start最近的未标记顶点,暂时记为k;</span></span><br><span class="line">            <span class="keyword">int</span> dmin = Integer.MAX_VALUE;  <span class="comment">//临时距离;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//内循环找到一个距离start最近的点;</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">                <span class="keyword">if</span> (visited[i] == <span class="number">0</span> &amp;&amp; weight[start][i] &lt; dmin) &#123;</span><br><span class="line">                    dmin = weight[start][i];</span><br><span class="line">                    k = i;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//至此已经找到了一个距离start的最短点;</span></span><br><span class="line">            <span class="comment">//将新选出的顶点标记为已求出最短路径，且到start的最短路径就是dmin</span></span><br><span class="line">            shortPath[k] = dmin;</span><br><span class="line">            visited[k] = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//以k为中间点，修正从start到未访问各点的距离</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">                <span class="comment">//start不能到i;但是start可以到k,k可以到i,</span></span><br><span class="line">                <span class="keyword">if</span> (visited[i] == <span class="number">0</span> &amp;&amp; weight[k][i] != M &amp;&amp; weight[start][k] + weight[k][i] &lt; weight[start][i]) &#123;</span><br><span class="line">                    weight[start][i] = weight[start][k] + weight[k][i];</span><br><span class="line">                    path[i] = path[k] + <span class="string">"--&gt;"</span> + i;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//打印最短路径们;</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">"从"</span> + start + <span class="string">"出发到"</span> + i + <span class="string">"的最短路径为："</span> + path[i]);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"====================================="</span>);</span><br><span class="line">        <span class="keyword">return</span> shortPath;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>改进:基本用法中为了更好的展示,使用了邻接矩阵,这需要更大的内存空间,一个改进方法是使用邻接链表;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">buildGraph</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    HashMap&lt;String, Vertex&gt; nodes = <span class="keyword">new</span> HashMap&lt;String, Vertex&gt;();</span><br><span class="line">    nodes.put(<span class="string">"a"</span>, <span class="keyword">new</span> Vertex(<span class="string">"a"</span>));</span><br><span class="line">    nodes.put(<span class="string">"b"</span>, <span class="keyword">new</span> Vertex(<span class="string">"b"</span>));</span><br><span class="line">    nodes.put(<span class="string">"c"</span>, <span class="keyword">new</span> Vertex(<span class="string">"c"</span>));</span><br><span class="line">    nodes.put(<span class="string">"d"</span>, <span class="keyword">new</span> Vertex(<span class="string">"d"</span>));</span><br><span class="line">    nodes.put(<span class="string">"e"</span>, <span class="keyword">new</span> Vertex(<span class="string">"e"</span>));</span><br><span class="line"></span><br><span class="line">    nodes.get(<span class="string">"a"</span>).map.put(nodes.get(<span class="string">"b"</span>), <span class="keyword">new</span> Edge(nodes.get(<span class="string">"a"</span>), nodes.get(<span class="string">"b"</span>), <span class="number">10</span>));</span><br><span class="line">    nodes.get(<span class="string">"a"</span>).map.put(nodes.get(<span class="string">"d"</span>), <span class="keyword">new</span> Edge(nodes.get(<span class="string">"a"</span>), nodes.get(<span class="string">"d"</span>), <span class="number">30</span>));</span><br><span class="line">    nodes.get(<span class="string">"a"</span>).map.put(nodes.get(<span class="string">"e"</span>), <span class="keyword">new</span> Edge(nodes.get(<span class="string">"a"</span>), nodes.get(<span class="string">"e"</span>), <span class="number">100</span>));</span><br><span class="line"></span><br><span class="line">    nodes.get(<span class="string">"b"</span>).map.put(nodes.get(<span class="string">"c"</span>), <span class="keyword">new</span> Edge(nodes.get(<span class="string">"b"</span>), nodes.get(<span class="string">"c"</span>), <span class="number">50</span>));</span><br><span class="line"></span><br><span class="line">    nodes.get(<span class="string">"c"</span>).map.put(nodes.get(<span class="string">"e"</span>), <span class="keyword">new</span> Edge(nodes.get(<span class="string">"c"</span>), nodes.get(<span class="string">"e"</span>), <span class="number">10</span>));</span><br><span class="line"></span><br><span class="line">    nodes.get(<span class="string">"d"</span>).map.put(nodes.get(<span class="string">"c"</span>), <span class="keyword">new</span> Edge(nodes.get(<span class="string">"d"</span>), nodes.get(<span class="string">"c"</span>), <span class="number">20</span>));</span><br><span class="line">    nodes.get(<span class="string">"d"</span>).map.put(nodes.get(<span class="string">"e"</span>), <span class="keyword">new</span> Edge(nodes.get(<span class="string">"d"</span>), nodes.get(<span class="string">"e"</span>), <span class="number">60</span>));</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//节点,没有什么特别之处,和一个String的类型一样;</span></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Vertex</span> </span>&#123;</span><br><span class="line">    String key;</span><br><span class="line">    HashMap&lt;Vertex, Edge&gt; map = <span class="keyword">new</span> HashMap&lt;Vertex, Edge&gt;();  <span class="comment">//key:以Vertex为end边的节点,当前节点到key的距离;</span></span><br><span class="line"></span><br><span class="line">    Vertex(String key) &#123;</span><br><span class="line">        <span class="keyword">this</span>.key = key;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//边,包含了一个起始和一个终止节点,已经一个边的长度;</span></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Edge</span> </span>&#123;</span><br><span class="line">    Vertex start;</span><br><span class="line">    Vertex end;</span><br><span class="line">    <span class="keyword">int</span> Len;</span><br><span class="line">    <span class="keyword">boolean</span> used;</span><br><span class="line"></span><br><span class="line">    Edge(Vertex start, Vertex end, <span class="keyword">int</span> key) &#123;</span><br><span class="line">        <span class="keyword">this</span>.start = start;</span><br><span class="line">        <span class="keyword">this</span>.end = end;</span><br><span class="line">        <span class="keyword">this</span>.Len = key;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>



  </section>


  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/10/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/10/">10</a><span class="page-number current">11</span><a class="page-number" href="/page/12/">12</a><a class="page-number" href="/page/13/">13</a><a class="extend next" rel="next" href="/page/12/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>





        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">





      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>





    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>











  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
